package com.ciaojian.core.mapper;

import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ciaojian.core.enums.business.OrderStatusEnum;
import com.ciaojian.core.enums.business.WorkerApplyStatusEnum;
import com.ciaojian.core.enums.business.WorkerWorkerStatusEnum;
import com.ciaojian.core.model.*;
import com.ciaojian.core.model.Order;
import com.ciaojian.core.model.dto.LoginDTO;
import com.ciaojian.core.model.dto.WorkerDTO;
import com.ciaojian.core.model.vo.*;
import org.apache.ibatis.annotations.*;
import org.apache.ibatis.annotations.Param;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 发型师
 *
 * @author Atlakyn
 */
public interface WorkerMapper extends BaseMapper<Worker> {
    /*
     * =============================查询=========================================
     */

    /**
     * 查询发型师所属门店ID
     *
     * @param workerId /
     * @return /
     */
    @Select("SELECT store_id FROM d_worker WHERE id = #{workerId} ")
    Integer getStoreIdByWorkerId(Integer workerId);

    /*
     * =============================分割线=========================================
     */

    /**
     * 新增图片名字到数据库
     *
     * @param imagePath 图片路径
     */
    @Insert("INSERT INTO d_image_upload (image_path) VALUES(#{imagePath})")
    void saveImageUpload(String imagePath);

    @Update("UPDATE d_order SET `status` = -1 WHERE id = #{id}")
    void cancelOrder(@Param("id") Integer id);    // 取消用户订单

    @Select("SELECT id,url,title,`desc`,give FROM d_worker_photo WHERE user_id = #{userId}")
    List<WorkerPhoto> findWorkerPhoto(@Param("userId") String userId);     // 查询发型师作品

    @Delete("DELETE FROM d_worker_photo WHERE id = #{id}")
    void delWorkerPhoto(@Param("id") String id);    // 删除发型师作品

    /**
     * 查询班次
     *
     * @param storeId 门店ID
     * @return 班次
     */
    @Select("SELECT id,`desc`,show_desc,start_work_time,end_work_time FROM d_roster WHERE store_id LIKE '%${storeId}%'")
    List<Roster> findDRosterList(@Param("storeId") String storeId);

    /**
     * @Description: 新增请假记录
     * @Author: xiangchao
     * @Date: 2020/11/9 7:16 下午
     */
    void saveDCheckAskfor(DCheckAskfor data);

    @Select("SELECT DATE_FORMAT(#{date},'%H:%i') > '12:00'")
    Integer getAfternoon(@Param("date") String date);

    @Select("SELECT #{date} >= CURDATE()")
    Integer greaterDay(@Param("date") String date);   // 判断是否大于等于今天

    @Select("SELECT #{start} > #{end}")
    Integer startEndTime(@Param("start") String start, @Param("end") String end);

    void saveDWorkerPhoto(WorkerPhoto data);   // 新增发型师作品

    @Delete("DELETE FROM d_image_upload WHERE image_path = #{imagePath}")
    void delDImageUpload(@Param("imagePath") String imagePath);     // 新增到数据库的时候删除数据库图片

    @Select("SELECT COUNT(1) FROM d_worker_photo WHERE user_id = #{userId}")
    Integer getWorkerPhotoCount(@Param("userId") Integer userId);    // 查询发型师作品数量

    Integer thisMonthCount(@Param("id") String id);  // 查询本月请假次数

    DAttendance getAttendanceSummary(@Param("date") String date, @Param("id") String id);

    @Select("SELECT DAY(LAST_DAY(#{date}))")
    Integer getMoneyDay(@Param("date") String date);   // 获取某个月有多少天

    void setSqlMode();

    /**
     * 获取每个月最后一天
     *
     * @param date 月份时间
     * @return 每个月最后一天
     */
    @Select("SELECT LAST_DAY(#{date})")
    String getLastDate(@Param("date") String date);

    @Update("UPDATE d_worker SET worker_status = #{status} WHERE id = #{id}")
    void edidWorkerStatus(@Param("status") String status, @Param("id") Integer id);

    void saveDCheckUser(CheckUser data);

    @Delete("DELETE FROM d_check_user WHERE user_id = #{id} AND date = DATE(CURDATE()) AND type = #{type}")
    void delCheckUserDk(@Param("id") Integer id, @Param("type") String type);

    @Select("SELECT COUNT(1) FROM d_check_user WHERE user_id = #{id} AND date = DATE(CURDATE()) AND type = #{type}")
    Integer isCheckUserDk(@Param("id") Integer id, @Param("type") String type);

    /**
     * @Description: 修改订单状态
     * @Author: xiangchao
     * @Date: 2020/11/9 4:57 下午
     */
    @Select("UPDATE d_order SET `status` = #{status} WHERE id = #{id}")
    void updateOrderStatus(@Param("status") OrderStatusEnum status, @Param("id") Integer id);

    /**
     * 更新服务时间
     *
     * @param id 名字
     */
    @Update("UPDATE d_order SET service_time = NOW() WHERE id = #{id}")
    void updateServiceTime(@Param("id") Integer id);

    @Update("UPDATE d_order SET order_type = 9, pay_total = #{payTotal}, pay_time = NOW(), youzan_code = #{youzanCode} WHERE id = #{id}")
    void meituanOrder(@Param("id") Integer id, @Param("payTotal") String payTotal, @Param("youzanCode") String youzanCode);   // 修改为美团订单

    @Select("SELECT status FROM d_order WHERE id = #{id}")
    Integer getOrderStatus(@Param("id") Integer id);

    /**
     * @Description: 查询头部统计
     * @Author: xiangchao
     * @Date: 2020/11/9 12:56 下午
     */
    DHeaderCount getDHeaderCount(@Param("id") String id);

    /**
     * 查询发型师门店ID
     *
     * @param id 发型师 ID
     * @return 门店 ID
     */
    @Select("SELECT store_id FROM d_worker WHERE id = #{id} ")
    Integer getStoreIdById(@Param("id") Integer id);

    @Select("SELECT DATE_FORMAT(ADDDATE(#{eatTime}, INTERVAL 30 MINUTE),'%Y-%m-%d %H:%i:%s')")
    String addMinute30(@Param("eatTime") String eatTime); //   添加30分钟

    @Select("SELECT type,date,time FROM d_check_user WHERE user_id = #{id} AND date = DATE(CURDATE())")
    List<CheckUser> getTypeDate(String id);

    @Select("SELECT start_work_time, end_work_time\n" +
            "        FROM d_scheduling ds\n" +
            "                 LEFT JOIN d_roster dr ON dr.id = ds.roster_id " +
            "        WHERE ds.phone = #{phone}\n" +
            "          AND `name` = #{name}\n" +
            "          AND ds.date = DATE(CURDATE()) " +
            "AND ds.status = 1 " +
            "AND ds.type = 0")
    DCheckUserTimeVo getStartEndWorkTime(DCheckUserTime data);

    /**
     * 查询发型师状态
     *
     * @param id 发型师id
     * @return 发型师信息
     */
    @Select("SELECT worker_status,eat_time,id,telphone,name FROM d_worker WHERE id = #{id}")
    Worker getWorkerStatus(Integer id);


    /**
     * 获取发型师数据
     *
     * @param page      分页插件
     * @param storeId   店面 id
     * @param pageNo    页码
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @return 发型师数据
     */
    Page<WorkerDataVO> getWorkerData(Page<WorkerDataVO> page,
                                     @Param("startDate") Date startDate,
                                     @Param("endDate") Date endDate,
                                     @Param("storeId") Integer storeId,
                                     @Param("pageNo") Integer pageNo);


    /**
     * 获取发型师个人数据
     *
     * @param workerId  发型师 id
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @return 个人数据
     */
    PersonaDataVO getPersonalData(@Param("workerId") Integer workerId,
                                  @Param("startDate") Date startDate,
                                  @Param("endDate") Date endDate);


    /**
     * 查询门店下的发型师
     *
     * @param storeId 门店ID
     * @return 发型师数据列表
     */
    @Select("SELECT * FROM d_worker WHERE store_id = #{storeId} AND status != 8")
    @Results({
            @Result(column = "worker_id", property = "schedule", one = @One(select = "com.ciaojian.core.mapper.SchedulingMapper.findByWorkerAndCurDate"))
    })
    List<WorkerDTO> getWorkerByStoreId(@Param("storeId") Integer storeId);

    /**
     * 根据发型师名称查询发型师
     *
     * @param name 发型师名称
     * @return 发型师信息
     */
    @Select("SELECT * FROM d_worker WHERE name LIKE CONCAT('%',#{name} ,'%') AND status != 8")
    @Results({
            @Result(property = "store", column = "store_id", one = @One(select = "com.ciaojian.core.mapper.StoreMapper.selectStoreDTO"))
    })
    List<WorkerDTO> selectByName(@Param("name") String name);

    /**
     * 为其他接口做关联查询
     *
     * @param id 发型师 id
     * @return 发型师数据
     * @see com.ciaojian.core.mapper.SchedulingExamineMapper#findByStoreId(Integer, WorkerApplyStatusEnum, Page)
     */
    @Select("SELECT * FROM d_worker WHERE id = #{id} ")
    WorkerInfoVO getWorkerInfoById(@Param("id") Integer id);

    /**
     * 根据 id 查找 workerDTO
     *
     * @param id 发型师 id
     * @return 发型师数据
     */
    @Select("SELECT * FROM d_worker WHERE id = #{id} ")
    @Results({
            @Result(property = "store", column = "store_id", one = @One(select = "com.ciaojian.core.mapper.StoreMapper.selectStoreDTO")),
            @Result(property = "schedule", column = "id", one = @One(select = "com.ciaojian.core.mapper.SchedulingMapper.findByWorkerAndCurDate"))
    })
    WorkerDTO selectWorkerDTO(@Param("id") Integer id);

    /**
     * 根据 id 查询发型师名称
     *
     * @param id 发型师id
     * @return 发型师名称
     */
    @Select("SELECT name FROM d_worker WHERE id = #{id} ")
    String getWorkerNameById(@Param("id") Integer id);

    /**
     * 根据id查询发型师手机号
     *
     * @param id 发型师id
     * @return 发型师手机号
     */
    @Select("SELECT telphone FROM d_worker WHERE id = #{id}")
    String getWorkerPhoneById(Integer id);

    /**
     * 查询门店下某个班次未排班的发型师
     *
     * @param date     日期
     * @param rosterId 班次id
     * @param storeId  门店id
     * @return 未排班的发型师
     */
    List<Worker> findNotSchedule(@Param("date") Date date, @Param("rosterId") Integer rosterId, @Param("storeId") Integer storeId);

    /**
     * 根据 id 获取发型师数据
     *
     * @param id 发型师 id
     * @return 发型师 Vo
     */
    List<WorkerVo> getWorkerById(Integer id);

    @Select("SELECT type FROM d_worker WHERE id = #{id}")
    Integer getType(String id);

    /**
     * 登录
     *
     * @param phone 手机号
     * @return 发型师信息
     */
    @Select("SELECT dw.id,dw.`name`,dw.type,dw.avatar,dw.telphone AS telephone,ds.address,ds.title,ds.lat,ds.lng,dw.store_id " +
            "FROM d_worker dw " +
            "LEFT JOIN d_store ds ON ds.id = dw.store_id " +
            "WHERE dw.telphone = #{phone}")
    LoginDTO getByPhone(String phone);

    /**
     * 修改 openID 根据手机号
     *
     * @param phone  手机号
     * @param openId openid
     */
    @Update("UPDATE d_worker SET openid = #{openId}  WHERE telphone = #{phone}")
    void updateOpenId(String phone, String openId);

    /**
     * 发型师数据列表
     *
     * @param workerId   发型师id
     * @param startDate  开始时间
     * @param endDate    结束时间
     * @param storeId    门店Id
     * @param orderTypes 订单类型(in查询)
     * @return 发型师数据
     */
    Map<String, Object> findWorkerData(@Param("workerId") Integer workerId,
                                       @Param("startDate") Date startDate,
                                       @Param("endDate") Date endDate,
                                       @Param("storeId") Integer storeId,
                                       @Param("orderTypes") List<Integer> orderTypes);

    /**
     * 统计发型师会员订单数据
     *
     * @param workerId  发型师id
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @param storeId   门店Id
     * @return 发型师会员订单数据
     */
    @MapKey("id")
    Map<Integer, Map<String, Object>> findMemberOrderData(@Param("workerId") Integer workerId,
                                                          @Param("startDate") Date startDate,
                                                          @Param("endDate") Date endDate,
                                                          @Param("storeId") Integer storeId);

    /**
     * 获取发型师状态
     *
     * @param id 发型师 id
     * @return 发型师状态
     */
    WorkerWorkerStatusEnum getWorkerStatusById(@Param("id") Integer id);

    @Select("SELECT w.*, w.id AS wid,l.`title` AS dengji,s.`title` FROM d_worker w LEFT JOIN d_level l ON w.`level_id`=l.`id` LEFT JOIN d_store s ON  w.`store_id`=s.`id` " +
            "WHERE w.`id`=#{id}")
    WorkerVo getById(Integer id);

    /**
     * @Description: 查询发型师订单列表
     * @Author: xiangchao
     * @Date: 2020/11/9 3:06 下午
     */
    List<Map<String, Object>> findWorkerOrder(@Param("data") Map data, @Param("page") Page page);

    /**
     * 获取发型师订单
     *
     * @param page 分页插件
     * @param data 参数
     * @return /
     */
    Page<Map<String, Object>> getWorkerOrder(Page<Map<String, Object>> page,
                                             @Param("data") Map<String, Object> data);

    Integer getWorkerOrderCount(@Param("data") Map data);

    /**
     * 查询是否为有效会员
     *
     * @param userId 用户
     * @return 有效会员
     */
    @Select("SELECT COUNT(1) FROM d_user_member WHERE user_id = #{userId} AND TO_DAYS(due_date) > TO_DAYS(NOW())")
    Integer getMemBerCount(String userId);

    /**
     * @Description: 查询某个用户订单有多少
     * @Author: xiangchao
     * @Date: 2020/11/10 3:28 下午
     */
    Integer getUserOrderCount(CheckUser data);

    @Select("SELECT DATE_FORMAT(ADDDATE(#{serviceTime}, INTERVAL 10 MINUTE),'%Y-%m-%d %H:%i:%s')")
    String addMinute10(String serviceTime); //   添加10分钟

    @Select("SELECT (UNIX_TIMESTAMP(#{endTime}) - UNIX_TIMESTAMP(#{startTime}))")
    String finalTime(String endTime, String startTime);

    List<Integer> getWorkerFree(@Param("storeId") Integer storeId);

    List<WorkerVo> getWorkerByIdFree(@Param("storeId") Integer storeId);


    List<WorkerPriceVo> selectWorkerPrice(@Param("id") Integer id);

    FranchiseesWorkerVo getWorkerInfo(@Param("workerId") Integer workerId);
}
